package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetmealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetmealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    private SetmealDao setmealDao;
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;
    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录


    @Override
    public List<Map<String, Object>> findSetmealCount() {
        return setmealDao.findSetmealCount();
    }

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        //操作新增检查组 t_setmeal 表
        setmealDao.add(setmeal);
        //设置检查组和检查项的多对多关联关系,操作t_setmeal_checkgroup表
        Integer setmealId = setmeal.getId();
        if(checkgroupIds != null && checkgroupIds.length > 0){
            this.setSetmealAndCheckGroup(checkgroupIds, setmealId);
        }
        //将图片名称保存到Redis
        savePic2Redis(setmeal.getImg());

        //当添加套餐后需要重新生成静态页面(套餐列表页面 套餐详情页面)
        generateMobileStaticHtml();
    }

    public void generateMobileStaticHtml (){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setmealDao.findAll();

        //需要生成套餐列表静态页面
        generateMobileSetmealListStaticHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDataStaticHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListStaticHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据,用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面
    public void generateMobileSetmealDataStaticHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setmealDao.findById4Detail(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() +".html",map);
        }
    }

    //通用的方法,用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获取配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //将图片名称保存到Redis
    private void savePic2Redis(String pic){
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,pic);
    }


    //分页查询
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();

        PageHelper.startPage(currentPage,pageSize);

        Page<CheckGroup> page = setmealDao.findByCondition(queryString);
        return new PageResult(page.getTotal(),page.getResult());
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    @Override
    public List<Integer> findCheckGroupIdsBySetmealId(Integer id) {
        return setmealDao.findCheckGroupIdsBySetmealId(id);
    }

    @Override
    public void deleteById(Integer id) {
        long count = setmealDao.findCountSetmealId(id);

        if (count > 0) {
            throw new RuntimeException("当前套餐被引用，不能删除");
        }
        setmealDao.deleteAssocication(id);
        setmealDao.deleteById(id);
    }

    @Override
    public void edit(Integer[] checkgroupIds, Setmeal setmeal) {
        //修改检查主基本信息,操作检查组t_checkgroup表
        setmealDao.edit(setmeal);
        //清理房钱检查组关联的检查项,操作中间关系表t_checkgroup_checkitem表
        setmealDao.deleteAssocication(setmeal.getId());
        //重新建立当前检查组的检查项关联关系
        Integer setmealId = setmeal.getId();
        setSetmealAndCheckGroup(checkgroupIds, setmealId);

        //当编辑套餐后需要重新生成静态页面(套餐列表页面 套餐详情页面)
        generateMobileStaticHtml();
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao .findAll();
    }

    //通过ID查询套餐信息,和套餐关联的检查组,和检查组关联的检查项
    public Setmeal findById4Detail(int id) {
        return setmealDao.findById4Detail(id);
    }


    private void setSetmealAndCheckGroup(Integer[] checkgroupIds, Integer setmealId) {
        if (checkgroupIds != null && checkgroupIds.length > 0) {
            for (Integer checkgroupId : checkgroupIds) {
                HashMap<String, Integer> map = new HashMap<>();
                map.put("setmeal_id",setmealId);
                map.put("checkgroup_id",checkgroupId);
                setmealDao.setCheckGroupAndCheckItem(map);
            }
        }
    }


}
